
/**
 * @param {ListNode} headA
 * @param {ListNode} headB
 * @return {ListNode}
 */
var getIntersectionNode = function (headA, headB) {
    if (headA === null || headB === null) return null

    let headASet = new Set()

    let tempA = headA
    while (tempA) {
        headASet.add(tempA)
        tempA = tempA.next
    }

    let tempB = headB
    while (tempB) {
        if (headASet.has(tempB)) {
            return tempB
        }
        tempB = tempB.next
    }

    return null
};

/**
 * @param {ListNode} headA
 * @param {ListNode} headB
 * @return {ListNode}
 */
var getIntersectionNode = function (headA, headB) {
    if (headA === null || headB === null) return null

    let tempA = headA,
        tempB = headB

    // 如果headA和headB的长度相等，有相等的地方则返回相等处，否则最后都为null
    // 如果headA和headB的长度不等，则headA+headB的长度相等，有相等的地方则返回相等处，否则最后都为null
    while (tempA !== tempB) {
        tempA = tempA === null ? headB : tempA.next
        tempB = tempB === null ? headA : tempB.next
    }

    return tempA
};

function ListNode(val, next) {
    this.val = (val === undefined ? 0 : val)
    this.next = (next === undefined ? null : next)
}

let a = new ListNode(4)
a.next = new ListNode(1)
a.next.next = new ListNode(8)
a.next.next.next = new ListNode(4)
a.next.next.next.next = new ListNode(5)

let b = new ListNode(5)
b.next = new ListNode(6)
b.next.next = new ListNode(1)
b.next.next.next = new ListNode(8)
b.next.next.next.next = new ListNode(4)
b.next.next.next.next.next = new ListNode(5)
console.log(getIntersectionNode(a, b));